package com.ln.cmsln.service.impl.yang;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ln.cmsln.mapper.yang.ZixunMapper;
import com.ln.cmsln.pojo.entity.yang.Zixun;
import com.ln.cmsln.service.yang.ZixunService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Helen
 * @since 2022-03-31
 */
@Service
public class ZixunServiceImpl extends ServiceImpl<ZixunMapper, Zixun> implements ZixunService {
    @Resource
    private ZixunMapper zixunMapper;

    @Override
    public List<Zixun> findAll() {
        return zixunMapper.selectList(null);
    }

    @Override
    public void remove(Long zId) {
        zixunMapper.selectById(zId);
    }

    @Override
    public boolean update(Zixun zixun, String realPath, MultipartFile file) {
        if (zixun!=null){
            //查询页面信息
            Zixun photo1 = baseMapper.selectById(zixun.getzId());
            String imgUrl = photo1.getzListImg();
            File file1 = new File(realPath+imgUrl);
            file1.delete();
            try {
                //按照时间分组存储图片
                SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd/HH/mm");
                String format = df.format(new Date());
                //组装图片存储的路径
                String imagesUrl = "\\src\\main\\resources\\image\\"+format+"\\"+file.getOriginalFilename();
                realPath=realPath+imagesUrl;
                File file2 = new File(realPath);

                //没有该路径则创建
                if (!file2.exists()){
                    file2.mkdirs();
                }
                //写入文件
                file.transferTo(file2);
                //修改图片路径
                zixun.setzListImg(imagesUrl);
            } catch (Exception e){
                e.printStackTrace();
                return false;
            }
        }
        return baseMapper.updateById(zixun) > 0;
    }

    @Override
    public Zixun findById(Long zId) {
        Zixun zixun = baseMapper.selectById(zId);
        return zixun;
    }

    @Override
    public int add(Zixun zixun) {
        return baseMapper.insert(zixun);
    }
}
